package com.innovation.chengzhangriji.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;

import com.google.gson.JsonElement;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.Discover;
import com.innovation.chengzhangriji.DiscoverSaveComment;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.DiscoverResponse;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.model.CommentModel;
import com.innovation.chengzhangriji.ui.widget.CommentItemDecoration;
import com.innovation.chengzhangriji.ui.widget.CuteToolbar;
import com.innovation.chengzhangriji.ui.widget.DiscoverCommentAdapter;
import com.innovation.chengzhangriji.ui.widget.DiscoverCommentLoadHolder;
import com.innovation.chengzhangriji.ui.widget.DiscoverCommentViewHolder;
import com.orhanobut.logger.Logger;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

public class DiscoverCommentActivity extends BaseActivity implements CuteToolbar.OnClickCuteToolbarListener, DiscoverCommentAdapter.Observer, DiscoverCommentLoadHolder.OnClickLoadMoreListener, DiscoverCommentViewHolder.OnClickDiscoverCommentListener {

    private RecyclerView recyclerView;

    private DiscoverCommentAdapter adapter;

    private LoginInfo loginInfo;

    // 评论列表
    private ArrayList<CommentModel> mCommentModels = new ArrayList<CommentModel>();

    private int SIZE = 15;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 初始化视图
        setupViews();

        // 初始化数据
        setupData();
    }

    // 初始化视图
    public void setupViews() {
        setContentView(R.layout.activity_discover_comment);
        CuteToolbar toolbar = (CuteToolbar) findViewById(R.id.toolbar);
        toolbar.setOnClickCuteToolbarListener(this);
        recyclerView = (RecyclerView) findViewById(R.id.recycler);
        adapter = new DiscoverCommentAdapter();
        adapter.setObserver(this);
        adapter.setCommentListener(this);
        adapter.setLoadMoreListener(this);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new CommentItemDecoration());
    }

    // 初始化数据
    public void setupData() {

        // 当前登录信息
        loginInfo = Config.getLoginInfo(this);

        // 判断是否有新的评论或赞
        if(DatabaseManager.getInstance(this).getNewCommentCount(loginInfo.getUserID()) > 15) {
            // 只加载15条新的评论
            mCommentModels.addAll(DatabaseManager.getInstance(this)
                    .getComments(SIZE, System.currentTimeMillis(), loginInfo.getUserID()));
        } else {
            // 加载所有新的评论
            mCommentModels.addAll(DatabaseManager.getInstance(this).getNewOrOldComments(true, loginInfo.getUserID()));
        }
        // if(mCommentModels.size() == 0) {
            // 没有新的评论，直接取旧的评论
            // mCommentModels.addAll(DatabaseManager.getInstance(this).getOldComments(Config.QUERY_LENGTH, System.currentTimeMillis(), loginInfo.getUserID()));
        // }
        // 查询是否有旧的评论
        int oldCount = DatabaseManager.getInstance(this).getNewOrOldComments(false, loginInfo.getUserID()).size();
        if (oldCount == 0) {
            // 没有旧的评论信息
            adapter.setIsEnd(true);
        } else {
            // 有旧的评论
            adapter.setIsEnd(false);
        }
        recyclerView.setAdapter(adapter);

        // 清除新评论标记
        Config.cleanHasNewComment(this);
    }

    @Override
    public void onClickLeft() {
//        if (!getIntent().getBooleanExtra(Config.EXTRA_CAN_BACK, true)) {
//            Intent intent = new Intent(this, DiscoverActivity.class);
//            intent.putExtra(Config.EXTRA_CAN_BACK, false);
//            startActivity(intent);
//            finish();
//        } else {
            Intent data = new Intent(this, DiscoverActivity.class);
            data.putExtra("needRefresh", true);
            setResult(RESULT_OK, data);
            finish();
//        }
    }

    @Override
    public void onClickRight() {
        clearLocalComment();
    }


    @Override
    public int length() {
        return mCommentModels.size();
    }

    @Override
    public int type(int position) {
        if (mCommentModels.get(position).getDiscover().getType() == 1) {
            if (TextUtils.isEmpty(mCommentModels.get(position).getDiscover().getMilestone())) {
                return 0;
            } else {
                return 4;
            }
        }
        return mCommentModels.get(position).getDiscover().getType() - 1;
    }

    @Override
    public String userName(int position) {
        return mCommentModels.get(position).getComment().getMemberName();
    }

    @Override
    public String userUrl(int position) {
        return mCommentModels.get(position).getComment().getUserHeadUrl();
    }

    @Override
    public String comment(int position) {
        return mCommentModels.get(position).getComment().getContent();
    }

    @Override
    public boolean like(int position) {
        return mCommentModels.get(position).getComment().getCommentType().equals(2);
    }

    @Override
    public String time(int position) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.SIMPLIFIED_CHINESE);
        Date date = new Date(mCommentModels.get(position).getComment().getCreateTS());
        return sf.format(date);
    }

    @Override
    public String from(int position) {
        Discover content = mCommentModels.get(position).getDiscover();
        if(content != null) {
            return "来自 "+ content.getBabyName() + "的成长日记";
        }
        return "";
    }

    @Override
    public String imageUrl(int position) {
        Discover content = mCommentModels.get(position).getDiscover();
        if(content == null) {
            return "";
        }
        if(type(position) == DiscoverCommentAdapter.VIDEO) {
            return content.getScreenshot();
        } else if(type(position) == DiscoverCommentAdapter.PHOTO) {
            return DatabaseManager.getInstance(this).getDiscoverFirstPhoto(content.getDiaryID());
        }
        return "";
    }

    @Override
    public String duration(int position) {
        if(type(position) == DiscoverCommentAdapter.VIDEO) {
            Discover content = mCommentModels.get(position).getDiscover();
            if(content == null) {
                return "0''";
            }
            return content.getDuration().toString();
        }
        return "0''";
    }

    @Override
    public String text(int position) {
        Discover content = mCommentModels.get(position).getDiscover();
        if(content == null) {
            return "";
        }
        if(type(position) == DiscoverCommentAdapter.TEXT) {
            return content.getText();
        } else if (type(position) == DiscoverCommentAdapter.MILESTONE) {
            return content.getMilestone();
        }
        return "";
    }

    // 清空评论信息
    private void clearLocalComment() {
        new AlertDialog.Builder(this).setTitle("是否清空所有评论信息?").setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if(loginInfo != null) {
                    DatabaseManager.getInstance(DiscoverCommentActivity.this).deleteAllNewComments(loginInfo.getUserID());
                }
                mCommentModels.clear();
                adapter.notifyDataSetChanged();
            }
        }).setNegativeButton("取消", null).show();
    }

    @Override
    public void loadMore() {
        long lastCreateTs = System.currentTimeMillis();
        if(mCommentModels.size() > 0) {
            CommentModel model = mCommentModels.get(mCommentModels.size() - 1);
            lastCreateTs = model.getComment().getCreateTS();
        }
        ArrayList<CommentModel> models = DatabaseManager.getInstance(this).getComments(SIZE, lastCreateTs, loginInfo.getUserID());
        if(models.size() == 0) {
            adapter.setIsEnd(true);
        } else {
            mCommentModels.addAll(models);
            if(models.size() < SIZE) {
                adapter.setIsEnd(true);
            } else {
                adapter.setIsEnd(false);
            }
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onClickLayout(DiscoverCommentViewHolder holder) {
        final Discover discover = mCommentModels.get(holder.getLayoutPosition()).getDiscover();
        if(discover == null) {
            tipShow("日记已删除");
            return;
        }
        Client.requestSingleDiscover(this, loginInfo.getPhone(), loginInfo.getToken().getAccessToken(), discover.getDiaryID(), new ResponseHandler() {

            @Override
            public void onInnovationSuccess(JsonElement value) {
                super.onInnovationSuccess(value);
                Logger.json(value.toString());
                DiscoverResponse response = get(value.toString(), DiscoverResponse.class);
                if (response == null || response.getContent() == null) {
                    // 日记已被删除, 删除日记及所有评论
                    DatabaseManager.getInstance(DiscoverCommentActivity.this.getApplicationContext()).deleteDiscover(discover.getDiaryID());
                    // 没有获取到，操作时，提示日记已删除
                    tipShow("日记已删除");
                    return;
                } else {
                    // 点击日记跳转到日记详情页
                    Intent intent = new Intent(DiscoverCommentActivity.this, DiscoverCommentDetailActivity.class);
                    intent.putExtra("diaryId", discover.getDiaryID());
                    startActivity(intent);
                }
            }

        }, new Client.NetworkUnavailableListener() {
            @Override
            public void networkUnavailable() {
                // 判断本地的日记状态
                if (discover.getIsDelete()) {
                    tipShow("日记已删除");
                    return;
                }
                // 点击日记跳转到日记详情页
                Intent intent = new Intent(DiscoverCommentActivity.this, DiscoverCommentDetailActivity.class);
                intent.putExtra("diaryId", discover.getDiaryID());
                startActivity(intent);
            }
        });
    }

    @Override
    public void onClickHead(DiscoverCommentViewHolder holder) {
        // 点击头像跳转到个人主页
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 更改新评论的状态为 更早的评论
        setCommentStateToOld();
    }

    // 更改新评论的状态为 更早的评论
    private void setCommentStateToOld() {
        if(mCommentModels.size() > 0) {
            ArrayList<DiscoverSaveComment> comments = new ArrayList<>();
            for (CommentModel model : mCommentModels) {
                DiscoverSaveComment comment = model.getComment();
                if (comment.getIsNew()) {
                    comment.setIsNew(false);
                    comments.add(comment);
                }
            }
            if(comments.size() > 0) {
                DatabaseManager.getInstance(this).updateComments(comments);
            }
        }
    }
}
